<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="SMB名称" prop="smbName">
        <el-input
          v-model="queryParams.smbName"
          placeholder="请输入SMB名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="SMB路径" prop="smbPath">
        <el-input
          v-model="queryParams.smbPath"
          placeholder="请输入SMB路径"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="smbStatus">
        <el-select v-model="queryParams.smbStatus" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" ref="toolbar">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['business:smbMgmt:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          :disabled="single || isMounted"
          @click="handleUpdate"
          v-hasPermi="['business:smbMgmt:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          :disabled="multiple || isMounted"
          @click="handleDelete"
          v-hasPermi="['business:smbMgmt:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          @click="handleExport"
          v-hasPermi="['business:smbMgmt:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-refresh"
          @click="handleRefreshCache"
          v-hasPermi="['business:smbMgmt:refreshCache']"
        >刷新缓存</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <div ref="divTable" :style="'height:' + divHeight + 'px'">
      <el-table v-loading="loading" :data="smbMgmtList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="SMB名称" align="center" prop="smbName" />
        <el-table-column label="SMB路径" align="center" prop="smbPath" />
        <el-table-column label="用户名" align="center" prop="userName" />
        <el-table-column label="挂载状态" align="center" prop="mountStatus" >
          <template v-slot="scope">
            <dict-tag :options="dict.type.smb_mount_status" :value="scope.row.mountStatus"/>
           </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="smbStatus">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_status" :value="scope.row.smbStatus"/>
           </template>
        </el-table-column>
        <el-table-column label="创建人" align="center" prop="createBy" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ $parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              type="text"
              :icon="scope.row.mountStatus === 'UNMOUNT' ? 'el-icon-connection' : 'el-icon-link'"
              @click="changeMountStatus(scope.row)"
              v-hasPermi="['business:smbMgmt:changeMountStatus']"
              v-if="scope.row.smbStatus === 'NORMAL'"
            >{{ scope.row.mountStatus === 'UNMOUNT' ? '挂载' : '卸载'}}</el-button>
            <el-button
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['business:smbMgmt:edit']"
                v-if="scope.row.mountStatus === 'UNMOUNT'"
            >修改</el-button>
            <el-button
              type="text"
              :icon="scope.row.smbStatus === 'DELETED' ? 'el-icon-refresh-left' : 'el-icon-delete'"
              @click="handleChangeStatus(scope.row)"
              v-hasPermi="['business:smbMgmt:changeStatus']"
              v-if="scope.row.mountStatus === 'UNMOUNT'"
            >{{scope.row.smbStatus === 'DELETED' ? "恢复" : "删除" }}</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :pageRefs="this.$refs"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
      />
    </div>
    <!-- 添加或修改业务-SMB管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="82px" :disabled="dialogDisabled">
        <el-form-item label="SMB名称" prop="smbName">
          <el-input v-model="form.smbName" placeholder="请输入SMB名称" />
        </el-form-item>
        <el-form-item label="SMB路径" prop="smbPath">
          <el-input v-model="form.smbPath" placeholder="请输入SMB路径" />
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" show-password/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" clearable type="textarea" :rows="2" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-row>
          <el-col :span="12" style="text-align: left;">
            <el-button type="success" @click="testConnect" v-hasPermi="['business:smbMgmt:testConnection']" :disabled="dialogDisabled" :loading="testLoading">测试连接</el-button>
          </el-col>
          <el-col :span="12" style="text-align: right;">
            <el-button type="primary" @click="submitForm" :disabled="dialogDisabled">确 定</el-button>
            <el-button @click="cancel" :disabled="dialogDisabled">取 消</el-button>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSmbMgmt,
  getSmbMgmt,
  delSmbMgmt,
  addSmbMgmt,
  updateSmbMgmt,
  exportExcel,
  testConnection,
  updateChangeStatus,
  updateChangeMountStatus,
  isExistMountSMB,
  refreshCache
} from "@/api/business/smbMgmt";
import ResizeMixin from "@/layout/mixin/ResizeHandler";
import {isExistPublishedNotice} from "@/api/system/notice";

export default {
  name: "SmbMgmt",
  mixins: [ResizeMixin],
  dicts: ['sys_status', 'smb_mount_status'],
  data() {
    return {
      // div高度
      divHeight: 0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 业务-SMB管理表格数据
      smbMgmtList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        smbName: null,
        smbPath: null,
        smbStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        smbName: [
          { required: true, message: "smb名称不能为空", trigger: "blur" }
        ],
        smbPath: [
          { required: true, message: "smb共享路径不能为空", trigger: "blur" }
        ],
        userName: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" }
        ]
      },
      // 测试连接加载状态
      testLoading: false,
      // 弹出框禁用状态
      dialogDisabled: false,
      // 是否已挂载
      isMounted: true,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询业务-SMB管理列表 */
    getList() {
      this.loading = true;
      listSmbMgmt(this.queryParams).then(response => {
        this.smbMgmtList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        smbName: null,
        smbPath: null,
        userName: null,
        password: null,
        smbStatus: null,
        mountStatus: null,
        userId: null,
        deptId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.$resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.isMounted = selection.some(item => item.mountStatus === 'MOUNT');
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加SMB管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSmbMgmt(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改SMB管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSmbMgmt(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSmbMgmt(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('注意：此删除不可恢复，是否确认删除？').then(function() {
        return delSmbMgmt(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      exportExcel(this.queryParams)
    },
    /** 测试连接按钮 */
    testConnect(){
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.dialogDisabled = true; // 禁用对话框
          this.testLoading = true; // 显示加载状态
          testConnection(this.form).then(res => {
            this.dialogDisabled = false; // 恢复对话框
            this.testLoading = false; // 隐藏加载状态
            if (res.data === true) {
              this.$modal.msgSuccess("连接成功");
            } else {
              this.$modal.msgError("连接失败，请重新输入");
            }
          });
        }
      });
    },
    /** 删除或恢复按钮操作 */
    handleChangeStatus(row) {
      const ids = row.id || this.ids;
      let status = row.smbStatus === 'NORMAL'? '删除' : '恢复';
      this.$modal.confirm('是否确认' + status + '此数据项？').then(function() {
        row.smbStatus = row.smbStatus === 'NORMAL'? 'DELETED' : 'NORMAL';
        return updateChangeStatus({ ids: ids, status: row.smbStatus })
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(status + "成功");
      }).catch(() => {});
    },
    /** 挂载或卸载按钮操作 */
    changeMountStatus(row){
      const ids = row.id || this.ids;
      let status = row.mountStatus === 'MOUNT'? '卸载' : '挂载';
      this.$modal.confirm('是否确认' + status + '此数据项？').then(async () => {
        if (row.mountStatus === 'UNMOUNT') {
          const res = await isExistMountSMB(ids);
          if (res.data) {
            throw new Error();
          }
        }
        row.mountStatus = row.mountStatus === 'MOUNT'? 'UNMOUNT' : 'MOUNT';
        return updateChangeMountStatus({ ids: ids, status: row.mountStatus })
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(status + "成功");
      }).catch((action) => {
        if (action !== 'cancel' && action !== 'close') {
          this.$modal.msgError("当前已有挂载点，请卸载后重新挂载！");
        }
      });
    },
    /** 刷新缓存按钮操作 */
    handleRefreshCache(){
      refreshCache().then(() => {
        this.$modal.msgSuccess("刷新成功");
      });
    },
  }
};
</script>
